package com.newbe.security.config;

import com.newbe.security.entity.Permission;
import com.newbe.security.handler.MyAuthenticationFailureHandler;
import com.newbe.security.handler.MyAuthenticationSuccessHandler;
import com.newbe.security.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;

import java.util.List;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAuthenticationFailureHandler FailureHandler;
    @Autowired
    private MyAuthenticationSuccessHandler SuccessHandler;

    @Autowired
    private MyAuthenticationProvider myAuthenticationProvider;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         //注册AuthenticationProvider
       auth.authenticationProvider(myAuthenticationProvider);



    }
     @Override
    protected void configure(HttpSecurity http) throws Exception {
//        //1.对页面资源进行拦截和命名
//        http.authorizeRequests().antMatchers("/showOrder").hasAnyAuthority("showOrder");
//        http.authorizeRequests().antMatchers("/addOrder").hasAnyAuthority("addOrder");
//        http.authorizeRequests().antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder");
//        http.authorizeRequests().antMatchers("/updateOrder").hasAnyAuthority("updateOrder");

          //1.动态对资源进行授权
         ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests();
         List<Permission> permission = permissionMapper.findAllPermission();
         for (Permission pm: permission) {
             authorizeRequests.antMatchers(pm.getUrl()).hasAnyAuthority(pm.getPermTag());
         }

         //2.对登录界面允许所有用户访问
        http.authorizeRequests().antMatchers("/login").permitAll();

        //3.资源需要进行登录认证，且关闭跨域允许post表单请求，loginProcessingUrl：表单路径，loginPage：登录界面
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin()
                .loginPage("/login").loginProcessingUrl("/loginFrom")
                //添加成功和失败处理器
                .successHandler(SuccessHandler).failureHandler(FailureHandler)
                .and().csrf().disable();
    }

}